package org.fei.jdbc;

import org.fei.create.utils.Config;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Created by gaolianli on 2015/7/14.
 */
public class JDBCFactory {
    static String url = "";
    static String usr = "";
    static String psd = "";
    static String driver = "";
    static {
        Properties prop = new Properties();
        InputStream in = Object.class.getResourceAsStream("/config.properties");
        try {
            prop.load(in);
            url = prop.getProperty("jdbc.url").trim();
            usr = prop.getProperty("jdbc.user").trim();
            psd = prop.getProperty("jdbc.pwd").trim();
            driver = prop.getProperty("jdbc.driver").trim();
            Config.init(prop);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getInstance(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, usr, psd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void closeConn(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {

        Connection conn = JDBCFactory.getInstance();
        Statement st = null;
        try {
            st = conn.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM tbx_textbook_t");
            while (rs.next()) {
                System.out.print(rs.getString(1));
                System.out.print("  ");
                System.out.println(rs.getString(2));
            }
            rs.close();
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCFactory.closeConn(conn);
        }


    }
}
